const app = getApp()
const api = require('../../utils/api')
const healthApi = require('../../utils/api/health')
const { getEmojiByName } = require('../../utils/emojiMap')
const request = require('../../utils/request')
const util = require('../../utils/util')
const DeviceSyncManager = require('../../utils/deviceSync')

Page({
  // 页面的初始数据
  data: {
    userInfo: {
      nickName: '用户',
      avatarUrl: '/assets/images/default-avatar.png',
    },
    connectedDevices: [],
    lastDataUpdateTime: '--',
    latestData: {
      glucose: '--',
      glucoseTrend: 'normal',
      bloodPressure: '--/--',
      bloodPressureTrend: 'normal',
      weight: '--',
      weightTrend: 'normal'
    },
    healthData: [
      { id: 1, name: '血糖', value: '--', unit: 'mmol/L', trend: 'normal' },
      { id: 2, name: '血压', value: '--/--', unit: 'mmHg', trend: 'normal' },
      { id: 3, name: '体重', value: '--', unit: 'kg', trend: 'normal' }
    ],
    services: [
      { id: 1, type: 'healthRecord', name: '健康记录', icon: 'record' },
      { id: 2, type: 'healthReport', name: '健康报告', icon: 'report' },
      { id: 3, type: 'healthReminder', name: '健康提醒', icon: 'reminder' },
      { id: 4, type: 'healthKnowledge', name: '健康知识', icon: 'knowledge' },
      { id: 5, type: 'dataAnalysis', name: '数据分析', icon: 'analysis' },
      { id: 6, type: 'healthTrend', name: '健康趋势', icon: 'trend' }
    ],
    riskLevel: '未评估',
    riskColor: '#999999', // 默认灰色
    riskDescription: '暂无风险评估数据，点击进行首次风险评估',
    lastAssessmentTime: '--',
    hasRiskAssessment: false, // 是否有风险评估记录
    healthTips: [
      '保持每日30分钟有氧运动，可有效降低血糖',
      '多吃蔬菜水果，少吃精制碳水化合物',
      '监测血糖的最佳时间是餐前和餐后2小时',
      '保持充足睡眠有助于血糖稳定',
      '适当补充膳食纤维，有助于控制血糖波动',
      '定期检查足部，预防糖尿病足的发生'
    ],
    healthTip: '',
    planCompletion: 0,
    dietPlanCompleted: false,
    exercisePlanCompleted: false,
    monitoringPlanCompleted: false,
    plans: [
      { id: 1, name: '饮食计划', type: 'diet', completed: false },
      { id: 2, name: '运动计划', type: 'exercise', completed: false },
      { id: 3, name: '监测计划', type: 'monitoring', completed: false }
    ],
    devices: [],
    weatherData: null
  },

  // 生命周期函数--监听页面显示
  async onShow() {
    // 获取用户信息
    await this.fetchUserInfo();
    
    // 获取最新的健康数据
    await this.fetchLatestHealthData();
    
    // 获取最新的风险评估数据
    await this.fetchLatestRiskAssessment();
    
    // 获取随机健康提示
    this.getRandomHealthTip();
    
    // 计算计划完成度
    this.calculatePlanCompletion();
    
    // 为设备、计划和服务添加emoji - 在获取数据后执行
    this.assignEmojis();
    
    // 获取已连接设备
    await this.fetchConnectedDevices();
    
    // 更新底部TabBar选中状态
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0
      });
    }
  },

  onLoad() {
    // 页面加载时执行的逻辑
    console.log('健康页面加载完成');
  },

  // 为设备、计划和服务添加emoji
  assignEmojis() {
    // 处理设备
    const devices = this.data.devices.map(item => {
      return { ...item, emoji: getEmojiByName(item.name) };
    });
    
    // 处理计划
    const plans = this.data.plans.map(item => {
      return { ...item, emoji: getEmojiByName(item.name) };
    });
    
    // 处理服务
    const services = this.data.services.map(item => {
      return { ...item, emoji: getEmojiByName(item.name) };
    });
    
    // 处理健康数据
    const healthData = this.data.healthData.map(item => {
      return { ...item, emoji: getEmojiByName(item.name) };
    });
    
    this.setData({
      devices,
      plans,
      services,
      healthData
    });
  },

  // 获取随机健康提示
  getRandomHealthTip() {
    const tips = this.data.healthTips;
    const randomIndex = Math.floor(Math.random() * tips.length);
    this.setData({
      healthTip: tips[randomIndex]
    });
  },

  // 刷新健康提示
  refreshTip() {
    this.getRandomHealthTip();
  },

  // 获取用户信息
  async fetchUserInfo() {
    const userInfo = app.globalData.userInfo;
    
    if (userInfo) {
      this.setData({
        userInfo: userInfo
      });
    } else {
      // 如果globalData中没有用户信息，尝试从API获取
      try {
        const response = await api.user.getUserInfo();
        if (response) {
          this.setData({
            userInfo: {
              nickName: response.name || '用户',
              avatarUrl: response.avatar || '/assets/images/default-avatar.png'
            }
          });
        }
      } catch (err) {
        console.error('获取用户信息失败', err);
      }
    }
  },

  // 获取最新的健康数据
  async fetchLatestHealthData() {
    try {
      console.log('[Health] 开始获取最新健康数据');
      
      // 从API获取最新数据
      const now = new Date();
      const yesterday = new Date(now);
      yesterday.setDate(now.getDate() - 7); // 获取一周内数据
      
      // 1. 获取血糖数据
      const glucoseData = await api.health.getRecords({ 
        type: 'glucose',
        startDate: yesterday.toISOString(),
        endDate: now.toISOString(),
        limit: 20
      });
      
      // 2. 获取血压数据
      const bloodPressureData = await api.health.getRecords({
        type: 'bloodpressure',
        startDate: yesterday.toISOString(),
        endDate: now.toISOString(),
        limit: 20
      });
      
      // 3. 获取体重数据
      const weightData = await api.health.getRecords({
        type: 'weight',
        startDate: yesterday.toISOString(),
        endDate: now.toISOString(),
        limit: 20
      });
      
      console.log('[Health] 获取到的数据：', { 
        glucose: glucoseData.length, 
        bloodPressure: bloodPressureData.length, 
        weight: weightData.length 
      });
      
      // 处理和更新UI
      let latestData = {
        glucose: '--',
        glucoseTrend: 'normal',
        bloodPressure: '--/--',
        bloodPressureTrend: 'normal',
        weight: '--',
        weightTrend: 'normal'
      };
      
      // 更新最后数据更新时间
      const updateTime = now.getHours() + ':' + now.getMinutes().toString().padStart(2, '0');
      this.setData({ lastDataUpdateTime: updateTime });
      
      // 处理血糖数据
      if (glucoseData && glucoseData.length > 0) {
        latestData.glucose = parseFloat(glucoseData[0].value).toFixed(1);
        
        // 计算趋势
        if (glucoseData.length >= 2) {
          const current = parseFloat(glucoseData[0].value);
          const previous = parseFloat(glucoseData[1].value);
          
          if (current > previous + 0.5) {
            latestData.glucoseTrend = 'up';
          } else if (current < previous - 0.5) {
            latestData.glucoseTrend = 'down';
          }
        }
      }
      
      // 处理血压数据
      if (bloodPressureData && bloodPressureData.length > 0) {
        const systolic = bloodPressureData[0].systolic;
        const diastolic = bloodPressureData[0].diastolic;
        latestData.bloodPressure = `${systolic}/${diastolic}`;
        
        // 计算趋势
        if (bloodPressureData.length >= 2) {
          const currentSystolic = bloodPressureData[0].systolic;
          const previousSystolic = bloodPressureData[1].systolic;
          
          if (currentSystolic > previousSystolic + 5) {
            latestData.bloodPressureTrend = 'up';
          } else if (currentSystolic < previousSystolic - 5) {
            latestData.bloodPressureTrend = 'down';
          }
        }
      }
      
      // 处理体重数据
      if (weightData && weightData.length > 0) {
        latestData.weight = parseFloat(weightData[0].value).toFixed(1);
        
        // 计算趋势
        if (weightData.length >= 2) {
          const current = parseFloat(weightData[0].value);
          const previous = parseFloat(weightData[1].value);
          
          if (current > previous + 0.5) {
            latestData.weightTrend = 'up';
          } else if (current < previous - 0.5) {
            latestData.weightTrend = 'down';
          }
        }
      }
      
      // 更新数据
      this.setData({
        latestData: latestData,
        healthData: [
          { id: 1, name: '血糖', value: latestData.glucose, unit: 'mmol/L', trend: latestData.glucoseTrend },
          { id: 2, name: '血压', value: latestData.bloodPressure, unit: 'mmHg', trend: latestData.bloodPressureTrend },
          { id: 3, name: '体重', value: latestData.weight, unit: 'kg', trend: latestData.weightTrend }
        ]
      });
      
    } catch (e) {
      console.error('获取健康数据失败', e);
      wx.showToast({
        title: '获取数据失败',
        icon: 'none'
      });
    }
  },

  // 获取最新风险评估数据
  async fetchLatestRiskAssessment() {
    try {
      console.log('[Health] 开始获取最新风险评估数据');
      
      // 调用风险评估API获取最新评估记录
      const latestAssessment = await healthApi.getLatestRiskAssessment();
      console.log('[Health] 获取到的风险评估数据:', latestAssessment);
      
      if (latestAssessment) {
        // 有风险评估记录
        const { result, timestamp } = latestAssessment;
        
        // 格式化日期
        const date = new Date(timestamp);
        const formattedDate = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
        
        // 设置风险等级对应的颜色
        let riskColor;
        switch (result.riskLevel) {
          case '低风险':
            riskColor = '#45bb5f'; // 绿色
            break;
          case '中风险':
            riskColor = '#ff9f43'; // 黄色
            break;
          case '高风险':
            riskColor = '#ff5a5f'; // 红色
            break;
          default:
            riskColor = '#999999'; // 灰色
        }
        
        // 更新UI
        this.setData({
          riskLevel: result.riskLevel,
          riskColor: riskColor,
          riskDescription: result.description || this.getRiskDescriptionByLevel(result.riskLevel),
          lastAssessmentTime: formattedDate,
          hasRiskAssessment: true
        });
      } else {
        // 没有风险评估记录
        this.setData({
          riskLevel: '未评估',
          riskColor: '#999999', // 灰色
          riskDescription: '暂无风险评估数据，点击进行首次风险评估',
          lastAssessmentTime: '--',
          hasRiskAssessment: false
        });
      }
    } catch (e) {
      console.error('获取风险评估数据失败', e);
      // 设置默认状态
      this.setData({
        riskLevel: '未知',
        riskColor: '#999999',
        riskDescription: '获取风险评估数据失败，请稍后重试',
        lastAssessmentTime: '--',
        hasRiskAssessment: false
      });
    }
  },
  
  // 根据风险等级获取描述文本
  getRiskDescriptionByLevel(level) {
    switch (level) {
      case '低风险':
        return '根据您的健康数据，当前患糖尿病风险较低，建议保持良好生活习惯';
      case '中风险':
        return '您的风险处于糖尿病前期范围，建议调整生活方式，定期监测血糖';
      case '高风险':
        return '您的风险较高，建议尽快咨询医生并进行专业评估';
      default:
        return '暂无风险评估数据，点击进行风险评估';
    }
  },

  // 评估风险等级 - 不再使用此方法，通过API获取最新风险评估结果
  assessRiskLevel(healthData) {
    // 此方法已被fetchLatestRiskAssessment替代
    console.log('[Health] assessRiskLevel方法已不再使用');
  },

  // 计算计划完成度
  calculatePlanCompletion() {
    // 计算三个计划的完成度
    let completedCount = 0;
    if (this.data.dietPlanCompleted) completedCount++;
    if (this.data.exercisePlanCompleted) completedCount++;
    if (this.data.monitoringPlanCompleted) completedCount++;
    
    const planCompletion = Math.round((completedCount / 3) * 100);
    
    this.setData({
      planCompletion: planCompletion
    });
  },

  // 前往记录页面
  goToRecord() {
    wx.navigateTo({
      url: '/pages/record/record?type=combined'
    });
  },

  // 前往风险评估页面
  goToRiskAssessment() {
    wx.navigateTo({
      url: '/pages/riskAssessment/riskAssessment'
    });
  },

  // 前往详情页面
  goToDetail(e) {
    const type = e.currentTarget.dataset.type;
    let url = '';
    
    switch (type) {
      case 'glucose':
        url = '/pages/bloodsugardetail/bloodsugardetail';
        break;
      case 'bloodPressure':
        url = '/pages/bloodPressureDetail/bloodPressureDetail';
        break;
      case 'weight':
        url = '/pages/weightDetail/weightDetail';
        break;
    }
    
    if (url) {
      wx.navigateTo({
        url: url
      });
    }
  },

  // 前往预防计划页面
  goToPreventionPlan() {
    wx.navigateTo({
      url: '/pages/preventionPlan/preventionPlan'
    });
  },

  // 前往饮食计划页面
  goToDietPlan() {
    wx.navigateTo({
      url: '/pages/diet/diet'
    });
  },

  // 前往运动计划页面
  goToExercisePlan() {
    wx.navigateTo({
      url: '/pages/exercise/exercise'
    });
  },

  // 前往监测计划页面
  goToMonitoringPlan() {
    wx.navigateTo({
      url: '/pages/monitoring/monitoring'
    });
  },

  // 前往设备连接页面
  goToDeviceConnect(e) {
    // 可以传递设备类型参数，或直接进入选择界面
    const deviceType = e.currentTarget.dataset.type || '';
    const url = deviceType ? 
      `/pages/deviceConnect/deviceConnect?deviceType=${deviceType}` : 
      '/pages/deviceConnect/deviceConnect';
    
    wx.navigateTo({ url });
  },

  // 连接设备
  connectDevice(e) {
    const device = e.currentTarget.dataset.device;
    console.log('跳转到设备连接页面', device);
    
    // 导航到设备连接页面，并传递设备类型参数
    wx.navigateTo({
      url: `/pages/deviceConnect/deviceConnect?deviceType=${device.type}`
    });
  },

  // 前往健康知识页面
  goToKnowledge() {
    wx.navigateTo({
      url: '/pages/healthKnowledge/healthKnowledge'
    });
  },

  // 前往健康知识详情页面
  goToKnowledgeDetail(e) {
    const knowledgeId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/healthKnowledgeDetail/healthKnowledgeDetail?id=${knowledgeId}`
    });
  },

  // 点击服务
  onServiceTap(e) {
    const type = e.currentTarget.dataset.type;
    
    switch (type) {
      case 'healthRecord':
        wx.navigateTo({
          url: '/pages/healthRecord/healthRecord'
        });
        break;
      case 'healthReport':
        wx.navigateTo({
          url: '/pages/healthReport/healthReport'
        });
        break;
      case 'healthReminder':
        wx.navigateTo({
          url: '/pages/healthReminder/healthReminder'
        });
        break;
      case 'healthKnowledge':
        wx.navigateTo({
          url: '/pages/healthKnowledge/healthKnowledge'
        });
        break;
      case 'dataAnalysis':
        wx.navigateTo({
          url: '/pages/dataAnalysis/dataAnalysis'
        });
        break;
      case 'healthTrend':
        wx.navigateTo({
          url: '/pages/healthTrend/healthTrend'
        });
        break;
      default:
        break;
    }
  },

  // 前往健康趋势页面
  goToTrend() {
    wx.navigateTo({
      url: '/pages/healthTrend/healthTrend'
    });
  },

  // 前往数据分析页面
  goToAnalysis() {
    wx.navigateTo({
      url: '/pages/dataAnalysis/dataAnalysis'
    });
  },

  // 获取已连接设备列表
  async fetchConnectedDevices() {
    try {
      console.log('开始获取已连接设备列表');
      const response = await api.device.getDevices();
      console.log('设备API响应:', response);
      
      if (response && response.success && response.data && response.data.devices) {
        // 添加设备emoji映射
        const deviceEmojis = {
          'glucose': '🩸',
          'bloodPressure': '💓',
          'weight': '⚖️'
        };
        
        // 格式化最后同步时间
        const formattedDevices = response.data.devices.map(device => {
          // 获取设备类型对应的emoji
          const emoji = deviceEmojis[device.type] || '📱';
          
          // 格式化最后同步时间
          let lastSyncText = '未同步';
          if (device.lastSyncDate) {
            const syncDate = new Date(device.lastSyncDate);
            lastSyncText = `${syncDate.getMonth() + 1}月${syncDate.getDate()}日 ${syncDate.getHours()}:${String(syncDate.getMinutes()).padStart(2, '0')}`;
          }
          
          return {
            ...device,
            emoji,
            connected: device.connectionStatus === 'connected',
            lastSyncText
          };
        });
        
        console.log('格式化后的设备列表:', formattedDevices);
        
        this.setData({
          devices: formattedDevices,
          hasDevices: formattedDevices.length > 0
        });
      } else {
        console.log('没有找到已连接设备或API返回格式不正确');
        this.setData({
          devices: [],
          hasDevices: false
        });
      }
    } catch (err) {
      console.error('获取已连接设备失败', err);
      this.setData({
        devices: [],
        hasDevices: false
      });
    }
  },
  
  // 获取设备类型对应的emoji
  getDeviceEmoji(type) {
    const emojiMap = {
      'glucose': '🩸',
      'bloodPressure': '💓',
      'weight': '⚖️'
    };
    return emojiMap[type] || '📱';
  },

  // 同步设备数据
  async syncDeviceData(e) {
    const deviceId = e.currentTarget.dataset.id;
    const device = this.data.devices.find(item => item._id === deviceId);
    
    if (!device) {
      wx.showToast({
        title: '设备不存在',
        icon: 'none'
      });
      return;
    }
    
    // 显示加载
    wx.showLoading({
      title: '同步数据中...',
      mask: true
    });
    
    try {
      // 调用设备同步API
      const result = await DeviceSyncManager.connectAndSync(device);
      
      wx.hideLoading();
      
      if (result.success) {
        // 同步成功，刷新数据
        this.fetchLatestHealthData();
        wx.showToast({
          title: '数据同步成功',
          icon: 'success'
        });
      } else {
        wx.showToast({
          title: result.message || '同步失败',
          icon: 'none'
        });
      }
    } catch (error) {
      wx.hideLoading();
      console.error('同步数据失败:', error);
      
      wx.showToast({
        title: '同步失败',
        icon: 'none'
      });
    }
  },
})